package pannel.recipe;

import pannel.category.Category;
import pannel.category.CategoryDao;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.sql.SQLException;
import java.util.List;

public class RecipeDialog extends JDialog {
    private JTextField nameField;
    private JTextArea descriptionArea;
    private JComboBox<Category> categoryComboBox;
    private JTextField imagePathField;
    private JLabel previewLabel;
    private boolean confirmed = false;
    private Recipe recipe;
    private CategoryDao categoryDao;

    public RecipeDialog(Frame owner, String title, Recipe recipe) {
        super(owner, title, true);
        this.recipe = recipe;
        this.categoryDao = new CategoryDao();
        setupDialog();
    }

    private void setupDialog() {
        setLayout(new BorderLayout());
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 菜谱名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        mainPanel.add(new JLabel("菜谱名称:"), gbc);
        nameField = new JTextField(20);
        gbc.gridx = 1;
        gbc.gridwidth = 2;
        mainPanel.add(nameField, gbc);

        // 分类选择
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        mainPanel.add(new JLabel("所属分类:"), gbc);
        categoryComboBox = new JComboBox<>();
        loadCategories();
        gbc.gridx = 1;
        gbc.gridwidth = 2;
        mainPanel.add(categoryComboBox, gbc);

        // 菜谱描述
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        mainPanel.add(new JLabel("菜谱描述:"), gbc);
        descriptionArea = new JTextArea(3, 20);
        descriptionArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(descriptionArea);
        gbc.gridx = 1;
        gbc.gridwidth = 2;
        mainPanel.add(scrollPane, gbc);

        // 图片路径
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        mainPanel.add(new JLabel("图片路径:"), gbc);
        imagePathField = new JTextField(20);
        gbc.gridx = 1;
        mainPanel.add(imagePathField, gbc);

        JButton browseButton = new JButton("浏览");
        gbc.gridx = 2;
        mainPanel.add(browseButton, gbc);

        // 图片预览
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 3;
        previewLabel = new JLabel();
        previewLabel.setPreferredSize(new Dimension(200, 200));
        previewLabel.setHorizontalAlignment(JLabel.CENTER);
        previewLabel.setBorder(BorderFactory.createEtchedBorder());
        mainPanel.add(previewLabel, gbc);

        // 填充现有数据
        if (recipe != null) {
            nameField.setText(recipe.getName());
            descriptionArea.setText(recipe.getDescription());
            imagePathField.setText(recipe.getImagePath());
            updatePreview(recipe.getImagePath());
            
            // 设置选中的分类
            for (int i = 0; i < categoryComboBox.getItemCount(); i++) {
                Category category = categoryComboBox.getItemAt(i);
                if (category.getId().equals(recipe.getCategoryId())) {
                    categoryComboBox.setSelectedIndex(i);
                    break;
                }
            }
        }

        // 图片选择事件
        browseButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                public boolean accept(File f) {
                    String name = f.getName().toLowerCase();
                    return f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".png")
                            || name.endsWith(".gif") || name.endsWith(".jpeg");
                }

                public String getDescription() {
                    return "Image Files (*.jpg, *.png, *.gif, *.jpeg)";
                }
            });

            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                String path = fileChooser.getSelectedFile().getAbsolutePath();
                imagePathField.setText(path);
                updatePreview(path);
            }
        });

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton okButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");

        okButton.addActionListener(e -> {
            if (validateInput()) {
                confirmed = true;
                dispose();
            }
        });
        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(getOwner());
        setResizable(false);
    }

    private void loadCategories() {
        try {
            List<Category> categories = categoryDao.findAll();
            DefaultComboBoxModel<Category> model = new DefaultComboBoxModel<>();
            for (Category category : categories) {
                model.addElement(category);
            }
            categoryComboBox.setModel(model);
            
            // 设置渲染器来显示分类名称
            categoryComboBox.setRenderer(new DefaultListCellRenderer() {
                @Override
                public Component getListCellRendererComponent(JList<?> list, Object value, 
                        int index, boolean isSelected, boolean cellHasFocus) {
                    if (value != null) {
                        value = ((Category) value).getName();
                    }
                    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                }
            });
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载分类数据失败：" + e.getMessage());
        }
    }

    private void updatePreview(String imagePath) {
        if (imagePath != null && !imagePath.isEmpty()) {
            try {
                ImageIcon originalIcon = new ImageIcon(imagePath);
                Image image = originalIcon.getImage();
                Image scaledImage = image.getScaledInstance(200, 200, Image.SCALE_SMOOTH);
                previewLabel.setIcon(new ImageIcon(scaledImage));
            } catch (Exception e) {
                previewLabel.setIcon(null);
                previewLabel.setText("预览失败");
            }
        } else {
            previewLabel.setIcon(null);
            previewLabel.setText("无图片");
        }
    }

    private boolean validateInput() {
        String name = nameField.getText().trim();
        Category selectedCategory = (Category) categoryComboBox.getSelectedItem();
        String imagePath = imagePathField.getText().trim();

        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "菜谱名称不能为空");
            return false;
        }

        if (selectedCategory == null) {
            JOptionPane.showMessageDialog(this, "请选择分类");
            return false;
        }

        if (imagePath.isEmpty() || !new File(imagePath).exists()) {
            JOptionPane.showMessageDialog(this, "请选择有效的图片文件");
            return false;
        }

        return true;
    }

    public boolean showDialog() {
        setVisible(true);
        return confirmed;
    }

    public String getRecipeName() {
        return nameField.getText().trim();
    }

    public String getDescription() {
        return descriptionArea.getText().trim();
    }

    public Category getSelectedCategory() {
        return (Category) categoryComboBox.getSelectedItem();
    }

    public String getImagePath() {
        return imagePathField.getText().trim();
    }
} 